'use strict';

module.exports = app => {
  return class extends app.Controller {
    * index(ctx) {
        const query=ctx.request.query;
        const menuId=query.menuId;
        var pageParams='';
        if(query.pageParams){
            pageParams =JSON.parse(ctx.request.query.pageParams);
            if(!pageParams.order){
                pageParams.order=[['createdAt','DESC']];
            }
        }else {
            pageParams={
                pageNum:1,
                pageLimit:6,
                pageTotal:0,
                order:[['createdAt','DESC']]
            }
        }
        var offset=(pageParams.pageNum - 1) * pageParams.pageLimit;
        var articles=yield ctx.model.Article.findAndCount({where:{menuId:menuId},limit:pageParams.pageLimit,offset:offset,order:pageParams.order});
        pageParams.pageTotal=Math.ceil(articles.count/pageParams.pageLimit);
        console.log('*******************');
        console.log(new Date());
        yield ctx.body={
            data:articles.rows,
            pageParams:pageParams
        };

    }
    * show(ctx){
        const id=ctx.params.id;
        console.log(ctx.params);
        var article=yield ctx.model.Article.findById(id);
        article.view++;
        article.save();
        ctx.body=article;
    }
      * create(ctx){
          const formId=ctx.request.body.formId;
          const formData=ctx.request.body.form;
          const wxFormId=ctx.request.body.wxFormId;
          const wpid=ctx.request.body.wpid;
          var article=yield ctx.model.Formmsg.create({userId:ctx.user.id,formId:formId,content:JSON.stringify(formData)});
          var status=false;
          if(article){
              status=true;
              var user=yield ctx.model.User.findOne({where:{wechatId:wpid,isAdmin:1}});
              var result=yield ctx.curl('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+ctx.wechat.accessToken.accessToken,{
                  method:'POST',
                  contentType:'json',
                  dataType:'json',
                  data:{
                      touser:user.openid,
                      template_id:'RlWsrsSRNJDhmc48h5VFSINYCjRqJLFaFEL8xRzUgZU',
                      form_id:wxFormId,
                      data:{
                        keyword1:{
                            DATA:formData.name
                        },
                          keyword2:{
                              DATA:formData.old
                          },
                          keyword3:{
                              DATA:formData.phone
                          },
                          keyword4:{
                              DATA:formData.time
                          },
                      }
                  }
              });

          }
          ctx.body={status:status};
      }
  };
};
